package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;

public class My_UdpDictServer {
    private DatagramSocket socket=null;
    private HashMap<String, String> dict = new HashMap<>();

    public My_UdpDictServer(int port) throws SocketException {
       socket=new DatagramSocket(port);
        dict.put("blue", "蓝色");
        dict.put("red", "红色");
        dict.put("write", "白色");
        dict.put("black", "黑色");
    }
    public void start() throws IOException {
        System.out.println("服务器启动");

        while (true){
            DatagramPacket requestPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength(), "UTF-8");
            // 2. 根据请求计算响应(由于咱们这是一个回显服务, 2 省略)
            String response = process(request);
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req: %s, resp: %s\n",
                    requestPacket.getAddress().toString(), requestPacket.getPort(), request, response);
        }
    }
    public String process(String request) {
        return dict.getOrDefault(request, "该词无法被翻译!");
    }
    public static void main(String[] args) throws IOException {

        My_UdpDictServer server = new My_UdpDictServer(9091);
        server.start();
    }

}
